<?php

App::uses('AppController', 'Controller');

class KontaktController extends AppController {
    
    public $pageTitle = 'Kontakt';

    public function index() {
    }
    
    public function captcha() {
        $this->autoRender = false;
        
        $captcha = '';
        $buffer  = '012345679qwertyuiopasdfghjklzxcvbnm';
        for ($i=0; $i<6; $i++) {
            $captcha .= substr($buffer, rand(0, strlen($buffer)-1), 1);
        }
        $this->Session->write('captcha', $captcha);
        
        $width  = 80;
        $height = 30;
        $white  = new ImagickPixel('white');
        $font   = 'css/fonts/OxygenLight.ttf';
        $fontSize = 20;
        
        $img = new Imagick();
        $img->newImage($width, $height, $white);
        
        $draw = new ImagickDraw();
        $draw->setFillColor('grey');
        $draw->setFont($font);
        $draw->setFontSize($fontSize);
        
        $img->annotateImage($draw, 0, $height-5, 0, $captcha);
        
        $img->setImageFormat('png');
        header('Content-Type:image/png');
        die($img);
    }

    public function send() {
        $this->autoRender = false;
        $captcha = $this->Session->read('captcha');
        $timeout = 20;
        
        if ($this->request->is('post')) {
            $data = $this->data;
            
            $error = false;
            foreach ($data as $k=>$v) {
                if (empty($v)) {
                    $error = true;
                    $this->setFlash('Sva polja su obavezna!', 'error', $timeout);
                }
            }
            
            if (!$error && strtolower($data['captcha'])!=strtolower($captcha)) {
                $error = true;
                $this->setFlash('Uneti tekst nije isti kao na slici.', 'error', $timeout);
            }
            
            if (! $error) {
                $data = array();
                $this->setFlash('Poruka je uspešno prosleđena.', 'ok', $timeout);
            }
            
            $this->set('data', $data);
        }
        
        $this->render('index');
    }

}